package com.heima.media.task;

import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: itheima
 * @create: 2022-03-28 15:46
 */
@Slf4j
@Component
public class MediaTask {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    @Autowired
    private IWmNewsService wmNewsService;


    /**
     * 监听延迟发布自媒体文章消息：正式发布文章
     */
    @Async("leadnewsExecutor")
    public void handleMessage() {
        try {
            RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("article-publish");
            RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            //初始化发送测试消息
            delayedQueue.offer("init", 1, TimeUnit.SECONDS);
            //监听消息
            while (true) {
                String result = blockingDeque.poll(30, TimeUnit.SECONDS);
                if (result != null && !"init".equals(result)) {
                    System.out.println("接收到了延迟发布文章消息，自媒体文章ID：" + result);
                    WmNews wmNews = wmNewsService.getById(result);
                    auditService.audit(wmNews);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.error("延迟消息监听器：{}", e.getMessage());
        }
    }
}
